package com.czk.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 模拟redis的客户单往服务器存储数据
 *
 * @Author:ChenZhangKun
 * @Date: 2021/6/22 16:38
 */
public class ClientSimulate {
    public static void main(String[] args) throws IOException {
        String CRLF = "\r\n";
        Socket socket = new Socket("localhost", 6379);
        try (OutputStream outputStream = socket.getOutputStream()) {
            StringBuilder builder = new StringBuilder();
            builder.append("*3").append(CRLF)
                    .append("$3").append(CRLF).append("set").append(CRLF)
                    .append("$4").append(CRLF).append("key2").append(CRLF)
                    .append("$6").append(CRLF).append("value2").append(CRLF);
            outputStream.write(builder.toString().getBytes());
            outputStream.flush();
            try (InputStream inputStream = socket.getInputStream()) {
                byte[] buffer = new byte[1024];
                int len = 0;
                len = inputStream.read(buffer);
                if (len > 0) {
                    String s = new String(buffer, 0, len);
                    // 服务器回复 +OK
                    System.out.println(s);
                }
            }
        }

    }
}
